package com.xunqi.ad.advice;

import com.xunqi.ad.annotation.IgnoreResponseAdvice;
import com.xunqi.ad.vo.ResponseVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 统一响应处理
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-28 17:00
 **/
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    @SuppressWarnings("all")        //隐藏idea警告信息
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> converterType) {

        //某个类不被统一响应拦截(只要加了IgnoreResponseAdvice)就不会被拦截
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }

        //某个方法不被统一响应拦截(只要加了IgnoreResponseAdvice)就不会被拦截
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }

        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        ResponseVo<Object> responseVo = new ResponseVo<>(0,"");

        if (null == body) {
            return responseVo;
        } else if (body instanceof ResponseVo) {
            responseVo = (ResponseVo<Object>) body;
        } else {
            responseVo.setData(body);
        }

        return responseVo;
    }
}
